from pydantic_settings import BaseSettings
from typing import Optional
import os
import multiprocessing

class DatabaseSettings(BaseSettings):
    """数据库连接配置"""
    postgres_user: str = "jiulang"
    postgres_password: str = "999999999"
    postgres_db: str = "postgres"
    postgres_host: str = "175.178.98.6"
    postgres_port: int = 9932
    
    # 连接池配置
    db_pool_size: int = multiprocessing.cpu_count() * 2  # 基础连接数
    db_max_overflow: int = 20  # 最大溢出连接数
    db_pool_timeout: int = 30  # 连接获取超时时间(秒)
    db_pool_recycle: int = 1800  # 连接回收时间(秒)
    
    # 心跳检测配置
    db_heartbeat_enabled: bool = True
    db_heartbeat_interval: int = 300  # 5分钟
    
    # 重连配置
    db_reconnect_enabled: bool = True
    db_reconnect_max_retries: int = 3
    db_reconnect_retry_interval: int = 5  # 重试间隔秒数
    
    @property
    def database_url(self) -> str:
        """构建PostgreSQL数据库连接URL"""
        return (
            f"postgresql+asyncpg://{self.postgres_user}:{self.postgres_password}"
            f"@{self.postgres_host}:{self.postgres_port}/{self.postgres_db}"
        )

class RedisSettings(BaseSettings):
    """Redis连接配置"""
    redis_host: str = "175.178.98.6"
    redis_port: int = 6379
    redis_db: int = 0
    redis_password: Optional[str] = None
    redis_pool_size: int = 20  # 连接池大小
    
    # 缓存配置
    cache_ttl_default: int = 300  # 默认缓存过期时间(秒)
    cache_ttl_short: int = 60  # 短期缓存过期时间(秒)
    cache_ttl_medium: int = 600  # 中期缓存过期时间(秒)
    cache_ttl_long: int = 3600  # 长期缓存过期时间(秒)
    
    @property
    def redis_url(self) -> str:
        """构建Redis连接URL"""
        auth = f":{self.redis_password}@" if self.redis_password else ""
        return f"redis://{auth}{self.redis_host}:{self.redis_port}/{self.redis_db}"

class Settings(BaseSettings):
    """应用配置类"""
    # 应用配置
    app_name: str = "课程表后端服务"
    debug: bool = True
    log_level: str = "INFO"
    
    # 数据库和Redis配置
    db: DatabaseSettings = DatabaseSettings()
    redis: RedisSettings = RedisSettings()
    
    class Config:
        env_file = (".env", ".env.example")
        env_file_encoding = "utf-8"
        case_sensitive = False

# 全局配置实例
settings = Settings()
